package com.example.demo.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

@Slf4j
public class HttpSSLPostUtil
{

    private static int socketTimeout = 5000;

    private static int connectTimeout = 5000;

    private static int requestTimeout = 5000;

    /**
     * httpclient证书post请求类
     *
     * @param certLocalPath 证书存放地址
     * @param mchId         商户号
     * @param url           请求地址
     * @param reqXML        请求参数，xml格式
     * @return
     */
    public static String SSLPost(String certLocalPath, String mchId, String url, String reqXML)
    {
        log.info("创建httpClient......");

        try
        {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File(certLocalPath));
            try
            {
                keyStore.load(instream, mchId.toCharArray());
            } finally
            {
                instream.close();
            }

            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout).setSocketTimeout(socketTimeout).build();

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).build();
            log.info("创建httpClient成功......");

            String result = null;
            HttpPost httpPost = new HttpPost(url);
            StringEntity postEntity = new StringEntity(reqXML, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(postEntity);
            log.info("executing request" + httpPost.getRequestLine());
            try
            {
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            } catch (Exception e)
            {
                throw new Exception("http get throw Exception", e);
            } finally
            {
                httpPost.releaseConnection();
            }

            return result;
        } catch (Exception e)
        {
            throw new RuntimeException("创建 httpclient失败......", e);
        }
    }
}
